package news.service;

import news.dao.LoginDao;
import news.model.Admin;
import news.model.CommonResult;
import news.model.Menu;
import news.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class LoginService {
    @Autowired
    LoginDao loginDao;


    public CommonResult login(Admin admin){
        //把传过来的明码加密
        admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
        Admin a = loginDao.login(admin);
        CommonResult commonResult = null;
        if(a != null){
            String token = JWTUtil.getToken(a);
            a.setAdminToken(token);
            commonResult = new CommonResult(200,a,"登陆成功");
            return commonResult;
        }else{
            commonResult = new CommonResult(201,"登陆失败");
            return commonResult;
        }

    }

    public List<Menu> menus(String adminToken) {
        int adminId = JWTUtil.getTokenInfo(adminToken).getClaim("id").asInt();
        List<Menu> menus = loginDao.menus(adminId);
        return menus;
    }
}
